<?php
class LoginController extends Zend_Controller_Action{
	private $_auth;
	public function init(){
		$this->_auth = Zend_Auth::getInstance();
	}
	public function indexAction(){
		$loginForm = new Application_Form_Login();
		$loginForm->setAction($this->view->url(array('controller' => 'login','action' => 'login'),'default',true));
		$this->view->form = $loginForm;
	}
	public function loginAction(){
		$request = $this->getRequest();

		if($request->isPost()){
			$form = new Application_Form_Login();
			$data = $request->getPost();

			if($form->isValid($data)){
				$values = $form->getValues();
				
				$pers = new Application_Model_DbTable_Personne();
				$salt = $pers->getSalt($values['login'])->salt;				
				
				$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table_Abstract::getDefaultAdapter(), 'auth_admin', 'login', 'password');
				$authAdapter->setIdentity($values['login']);
				$authAdapter->setCredential(sha1($values['password'].$salt));
				if ($this->_auth->authenticate($authAdapter)->isValid()) {
					$this->_auth->getStorage()->write($res = $authAdapter->getResultRowObject(null,'password'));
					Zend_Session::regenerateId();
					$this->_helper->redirector('index','index','admin');
				}else {
					$authAdapter->setTableName('auth_prof');
					if ($this->_auth->authenticate($authAdapter)->isValid()) {
						$this->_auth->getStorage()->write($res = $authAdapter->getResultRowObject(null,'password'));
						Zend_Session::regenerateId();
						$this->_helper->redirector('index','index','prof');
					}else {
						$authAdapter->setTableName('auth_etudiant');
						if ($this->_auth->authenticate($authAdapter)->isValid()) {
							$this->_auth->getStorage()->write($res = $authAdapter->getResultRowObject(null,'password'));
							Zend_Session::regenerateId();
							$this->_helper->redirector('index','index');
						}else{
							$this->_helper->redirector('deny','error');
						}
					}
				}
			}else{
				$this->view->form = $form;
			}
		} else {
			$this->_helper->redirector('index','login');
		}
	}

	public function logoutAction(){
		Zend_Auth::getInstance()->clearIdentity();
		Zend_Session::destroy();
		$this->_helper->redirector('index','index','default');
	}
}